package main

import (
	"database/sql"
	"fmt"
	"log"
	"net/http"

	"github.com/gin-gonic/gin"
	_ "github.com/go-sql-driver/mysql"
)

func Register(c *gin.Context) {
	dsn := "root:root@tcp(localhost:3306)/golang"
	// "账号：密码@tcp(localhost:端口号)/数据库名"
	db, err := sql.Open("mysql", dsn)
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	Username := c.PostForm("username")
	Password := c.PostForm("password")

	sqlStr := "INSERT INTO user (username, password) VALUES (?, ?);"
	res, err2 := db.Exec(sqlStr, Username, Password)

	fmt.Println(sqlStr)
	if err2 != nil {
		log.Fatal(err)
	}
	fmt.Println(res.RowsAffected())
	c.Redirect(http.StatusMovedPermanently, "/login_page")
}

func RegisterPage(c *gin.Context) {
	c.HTML(http.StatusOK, "register_page.html", 0)
}

func Login(c *gin.Context) {
	dsn := "root:root@tcp(localhost:3306)/golang"
	// "账号：密码@tcp(localhost:端口号)/数据库名"
	db, err := sql.Open("mysql", dsn)
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	Username := c.PostForm("username")
	Password := c.PostForm("password")

	sqlStr := "SELECT * FROM user WHERE username=? AND password=?;"
	fmt.Println(sqlStr)
	res, err2 := db.Query(sqlStr, Username, Password)
	if err2 != nil {
		log.Fatal(err)
	}
	defer res.Close()

	var username string
	var password string
	if res.Next() {
		err = res.Scan(&username, &password)
		if err != nil {
			log.Fatal(err)
		}
		userStatus = true                                 // 设置用户状态为已登录
		c.Redirect(http.StatusMovedPermanently, "/index") // 登录成功跳转到主页面
	} else {
		c.JSON(http.StatusUnauthorized, gin.H{
			"message": "用户名或密码错误",
		})
	}
}

func LoginPage(c *gin.Context) {
	c.HTML(http.StatusOK, "login_page.html", 0)
}

var userStatus bool

func Index(c *gin.Context) {
	if !userStatus { // 如果用户未登录，重定向到登录页面
		c.Redirect(http.StatusMovedPermanently, "/login_page")
		return
	}

	c.HTML(http.StatusOK, "index.html", 0)
}

func Student(c *gin.Context) {
	dsn := "root:root@tcp(localhost:3306)/golang"
	// "账号:密码@tcp(localhost:端口号)/数据库名"
	db, err := sql.Open("mysql", dsn)
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	sqlStr := "SELECT * FROM student"
	// "SELECT * FROM 表名"
	studentSlice := MySQLStudent(db, sqlStr)
	c.HTML(http.StatusOK, "student_page.html", gin.H{
		"student_slice": studentSlice, // 从数据库中查询到的结果
	})
}

type student struct {
	Id   int
	Name string
	Age  int
}

func MySQLStudent(db *sql.DB, sqlStr string) []student {
	rows, err := db.Query(sqlStr)
	if err != nil {
		log.Fatal(err)
	}
	defer rows.Close()

	students := make([]student, 0)

	for rows.Next() {
		stu1 := student{}
		if err := rows.Scan(&stu1.Id, &stu1.Name, &stu1.Age); err != nil {
			log.Fatal(err)
		}
		students = append(students, stu1)
	}
	return students
}

func Add(c *gin.Context) {
	dsn := "root:root@tcp(localhost:3306)/golang"
	// "账号:密码@tcp(localhost:端口号)/数据库名"
	db, err := sql.Open("mysql", dsn)
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	Id := c.PostForm("Id")
	Name := c.PostForm("Name")
	Age := c.PostForm("Age")

	sqlStr := "INSERT INTO student (id, name,age) VALUES (" + Id + ",'" + Name + "'," + Age + ");"
	fmt.Println(sqlStr)
	res, err2 := db.Exec(sqlStr)
	if err2 != nil {
		log.Fatal(err)
	}
	fmt.Println(res.RowsAffected())
	c.Redirect(http.StatusMovedPermanently, "/student_page")
}

func AddPage(c *gin.Context) {
	c.HTML(http.StatusOK, "add_page.html", 0)
}

func DeletePage(c *gin.Context) {
	c.HTML(http.StatusOK, "delete_page.html", 0)
}

func DeleteOneRow(c *gin.Context) {
	dsn := "root:root@tcp(localhost:3306)/golang"
	// "账号:密码@tcp(localhost:端口号)/数据库名"
	db, err := sql.Open("mysql", dsn)
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	Id := c.PostForm("Id")
	sqlStr := "DELETE FROM student WHERE id = " + Id + ";"
	fmt.Println(sqlStr)

	res, err2 := db.Exec(sqlStr)
	if err2 != nil {
		log.Fatal(err)
	}
	fmt.Println(res.RowsAffected())
	c.Redirect(http.StatusMovedPermanently, "/student_page")
}

func DeleteDirect(c *gin.Context) {
	dsn := "root:root@tcp(localhost:3306)/golang"
	// "账号:密码@tcp(localhost:端口号)/数据库名"
	db, err := sql.Open("mysql", dsn)
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	Id := c.PostForm("Id")

	fmt.Println(Id)
	c.Redirect(http.StatusMovedPermanently, "/student_page")
}

func UpdateOneRow(c *gin.Context) {
	dsn := "root:root@tcp(localhost:3306)/golang"
	db, err := sql.Open("mysql", dsn)
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	Id := c.PostForm("Id")
	Name := c.PostForm("Name")
	Age := c.PostForm("Age")

	sqlStr := "UPDATE student SET name='" + Name + "', age=" + Age + " WHERE id=" + Id + ";"
	fmt.Println(sqlStr)

	res, err := db.Exec(sqlStr)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(res.RowsAffected())
	c.Redirect(http.StatusMovedPermanently, "/student_page")
}
func UpdatePage(c *gin.Context) {
	c.HTML(http.StatusOK, "update_page.html", 0)
}

func Teacher(c *gin.Context) {
	dsn := "root:root@tcp(localhost:3306)/golang"
	// "账号:密码@tcp(localhost:端口号)/数据库名"
	db, err := sql.Open("mysql", dsn)
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()
	sqlStr := "SELECT * FROM teacher"
	// "SELECT * FROM 表名"
	teacherSlice := MySQLTeacher(db, sqlStr)
	c.HTML(http.StatusOK, "teacher_page.html", gin.H{
		"teacher_slice": teacherSlice, // 从数据库中查询到的结果
	})
}

type teacher struct {
	Name string
	Age  int
}

func MySQLTeacher(db *sql.DB, sqlStr string) []teacher {
	rows, err := db.Query(sqlStr)
	if err != nil {
		log.Fatal(err)
	}
	defer rows.Close()

	teachers := make([]teacher, 0)

	for rows.Next() {
		tea1 := teacher{}
		if err := rows.Scan(&tea1.Name, &tea1.Age); err != nil {
			log.Fatal(err)
		}
		teachers = append(teachers, tea1)
	}
	return teachers
}

func Book(c *gin.Context) {
	dsn := "root:root@tcp(localhost:3306)/golang"
	// "账号:密码@tcp(localhost:端口号)/数据库名"
	db, err := sql.Open("mysql", dsn)
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()
	sqlStr := "SELECT * FROM book"
	// "SELECT * FROM 表名"
	bookSlice := MySQLBook(db, sqlStr)
	c.HTML(http.StatusOK, "book_page.html", gin.H{
		"book_slice": bookSlice, // 从数据库中查询到的结果
	})
}

type book struct {
	Bookname string
	Author   string
}

func MySQLBook(db *sql.DB, sqlStr string) []book {
	rows, err := db.Query(sqlStr)
	if err != nil {
		log.Fatal(err)
	}
	defer rows.Close()

	books := make([]book, 0)

	for rows.Next() {
		bo1 := book{}
		if err := rows.Scan(&bo1.Bookname, &bo1.Author); err != nil {
			log.Fatal(err)
		}
		books = append(books, bo1)
	}
	return books
}

func Class(c *gin.Context) {
	dsn := "root:root@tcp(localhost:3306)/golang"
	// "账号:密码@tcp(localhost:端口号)/数据库名"
	db, err := sql.Open("mysql", dsn)
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()
	sqlStr := "SELECT * FROM class"
	// "SELECT * FROM 表名"
	classSlice := MySQLClass(db, sqlStr)
	c.HTML(http.StatusOK, "class_page.html", gin.H{
		"class_slice": classSlice, // 从数据库中查询到的结果
	})
}

type class struct {
	Classname string
	Datetime  int
}

func MySQLClass(db *sql.DB, sqlStr string) []class {
	rows, err := db.Query(sqlStr)
	if err != nil {
		log.Fatal(err)
	}
	defer rows.Close()

	classs := make([]class, 0)

	for rows.Next() {
		cl1 := class{}
		if err := rows.Scan(&cl1.Classname, &cl1.Datetime); err != nil {
			log.Fatal(err)
		}
		classs = append(classs, cl1)
	}
	return classs
}

func SetupRouter() *gin.Engine {
	router := gin.Default()
	router.LoadHTMLGlob("templates/*")
	router.Static("css", "./asset/css")
	router.GET("/index", Index)
	router.GET("/student_page", Student)
	router.POST("/login", Login)
	router.POST("/add", Add)
	router.GET("/add_page", AddPage)
	router.GET("/login_page", LoginPage)
	router.POST("/register", Register)
	router.GET("/register_page", RegisterPage)
	router.GET("/teacher_page", Teacher)
	router.GET("/book_page", Book)
	router.GET("/class_page", Class)
	router.POST("/delete_direct", DeleteDirect)
	router.POST("/delete_one_row", DeleteOneRow)
	router.GET("/delete_page", DeletePage)
	router.POST("/update_one_row", UpdateOneRow)
	router.GET("/update_page", UpdatePage)
	return router
}

func main() {
	router := SetupRouter()
	router.Run()
}
